package cn.kimming.wms.web.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

import cn.kimming.wms.anno.RequiredPermission;
import cn.kimming.wms.domain.Brand;
import cn.kimming.wms.domain.JsonMsg;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.IBrandService;
import lombok.Getter;

@Controller("brandAction")
@Scope("prototype")
public class BrandAction extends BaseAction {

	private static final long serialVersionUID = -2025659863219890382L;

	@Autowired
	private IBrandService brandService;
	
	@Getter
	private Brand brand = new Brand();
	
	@Getter 
	private QueryObject qo = new QueryObject();

	@Override
	@RequiredPermission("品牌列表")
	@InputConfig(methodName="input")
	public String execute() {
		try {
			ActionContext.getContext().put("objs", brandService.query(qo));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return LIST;
	}
	
	@RequiredPermission("品牌编辑")
	public String input() {
		try {
			if (brand.getId() != null) {
				brand = brandService.get(brand.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return INPUT;
	}

	@RequiredPermission("品牌保存和更新")
	public String saveOrUpdate() {
		if (brand.getId() != null) {
			try {
				brandService.update(brand);
				addActionMessage("更新成功!");
			} catch(Exception e) {
				e.printStackTrace();
				addActionError("系统异常,更新失败!");
			}
		} else {
			try {
				brandService.save(brand);
				addActionMessage("保存成功!");
			} catch(Exception e) {
				e.printStackTrace();
				addActionError("系统异常,更新失败!");
			}
		}
		return SUCCESS;
	}

	@RequiredPermission("品牌删除")
	public String delete() {
		try {
			if (brand.getId() != null) {
				brandService.delete(brand.getId());
				putJSON(new JsonMsg(true, "删除成功"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			putJSON(new JsonMsg(false, "系统异常,删除失败!"));
		}
		return NONE;
	}
	
	public void prepareSaveOrUpdate() throws Exception {
		if (brand.getId() != null) {
			brand = brandService.get(brand.getId());
		}
	}

}
